package org.example;

import java.io.IOException;
import org.apache.hadoop.conf.Configuration;
import org.apache.hadoop.fs.Path;
import org.apache.hadoop.io.*;
import org.apache.hadoop.mapreduce.Job;
import org.apache.hadoop.mapreduce.lib.input.FileInputFormat;
import org.apache.hadoop.mapreduce.lib.output.FileOutputFormat;
import org.apache.hadoop.mapreduce.Mapper;
import org.apache.hadoop.mapreduce.Reducer;

import java.time.DayOfWeek;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;
public class Task3Driver1 {
    public static class Task3Mapper1 extends Mapper<Object,Text,Text,IntWritable>{
        IntWritable one=new IntWritable(1);
        IntWritable zero=new IntWritable(0);
        @Override
        public void map(Object key,Text value,Context context) throws IOException, InterruptedException{
            String[] parts=value.toString().split(",");
            if(parts.length>=3) {
                Text userID = new Text(parts[0]);
                int purchase=Integer.parseInt(parts[1]);
                int redeem=Integer.parseInt(parts[2]);
                //根据活跃指标判定用户是否活跃
                if(purchase>0 || redeem>0){
                    context.write(userID,one);
                }
                else context.write(userID,zero);
            }
        }
    }

    public static class Task3Reducer1 extends Reducer<Text,IntWritable,Text,IntWritable>{
        private final IntWritable result = new IntWritable();
        @Override
        public void reduce(Text key,Iterable<IntWritable> values,Context context) throws IOException,InterruptedException{
            int activeDay=0;
            for(IntWritable val:values){
                activeDay+=val.get();
            }
            result.set(activeDay);
            context.write(key,result);
        }
    }

    public static void main(String[] args) throws Exception {
        Configuration conf = new Configuration();
        Job job = Job.getInstance(conf, "task3 activeDays");

        job.setJarByClass(Task3Driver1.class);
        job.setMapperClass(Task3Driver1.Task3Mapper1.class);
        job.setReducerClass(Task3Driver1.Task3Reducer1.class);

        job.setMapOutputKeyClass(Text.class);
        job.setMapOutputValueClass(IntWritable.class);
        job.setOutputKeyClass(Text.class);
        job.setOutputValueClass(IntWritable.class);

        FileInputFormat.addInputPath(job, new Path(args[0]));
        FileOutputFormat.setOutputPath(job, new Path(args[1]));

        System.exit(job.waitForCompletion(true) ? 0 : 1);
    }

}
